using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OrderingSystem.Core.Entities;
using OrderingSystem.Core.Interfaces;
using OrderingSystem.Infrastructure.Data;
using System.Security.Claims;

namespace OrderingSystem.API.Controllers
{
    [ApiController]
    [Route("chat")]
    public class ChatController : ControllerBase
    {
        private readonly IChatService _chatService;
        private readonly ApplicationDbContext _context;

        public ChatController(IChatService chatService, ApplicationDbContext context)
        {
            _chatService = chatService;
            _context = context;
        }

        /// <summary>
        /// 获取聊天列表
        /// </summary>
        [HttpGet("list")]
        [Authorize(Roles = "Admin")]
        public async Task<ActionResult<R>> GetChats()
        {
            var chats = await _chatService.GetChatsAsync();
            return Ok(new R
            {
                code = 0,
                msg = "获取成功",
                data = chats
            });
        }

        /// <summary>
        /// 获取用户聊天列表
        /// </summary>
        [HttpGet("user")]
        [Authorize]
        public async Task<ActionResult<R>> GetUserChats()
        {
            var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "0");
            var chats = await _chatService.GetUserChatsAsync(userId);
            return Ok(new R
            {
                code = 0,
                msg = "获取成功",
                data = chats
            });
        }

        /// <summary>
        /// 获取聊天详情
        /// </summary>
        [HttpGet("detail/{id}")]
        [Authorize]
        public async Task<ActionResult<R>> GetChat(long id)
        {
            var chat = await _chatService.GetChatAsync(id);
            if (chat == null)
            {
                return Ok(new R { code = 1, msg = "聊天记录不存在" });
            }

            var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "0");
            if (chat.userid != userId && !User.IsInRole("Admin"))
            {
                return Ok(new R { code = 1, msg = "无权查看此聊天记录" });
            }

            return Ok(new R
            {
                code = 0,
                msg = "获取成功",
                data = chat
            });
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        [HttpPost("send")]
        [Authorize]
        public async Task<ActionResult<R>> SendMessage([FromBody] SendMessageModel model)
        {
            var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "0");
            var chat = new Chat
            {
                userid = userId,
                LiaoTianNeiRong = model.Message,
                addtime = DateTime.Now,
                isreply = 0
            };

            var result = await _chatService.CreateChatAsync(chat);
            return Ok(new R
            {
                code = 0,
                msg = "发送成功",
                data = result
            });
        }

        /// <summary>
        /// 回复消息
        /// </summary>
        [HttpPost("reply/{id}")]
        [Authorize(Roles = "Admin")]
        public async Task<ActionResult<R>> ReplyMessage(long id, [FromBody] ReplyMessageModel model)
        {
            var chat = await _chatService.ReplyChatAsync(id, model.Reply);
            if (chat == null)
            {
                return Ok(new R { code = 1, msg = "聊天记录不存在" });
            }

            return Ok(new R
            {
                code = 0,
                msg = "回复成功",
                data = chat
            });
        }

        /// <summary>
        /// 删除聊天记录
        /// </summary>
        [HttpPost("delete/{id}")]
        [Authorize]
        public async Task<ActionResult<R>> DeleteChat(long id)
        {
            var chat = await _chatService.GetChatAsync(id);
            if (chat == null)
            {
                return Ok(new R { code = 1, msg = "聊天记录不存在" });
            }

            var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "0");
            if (chat.userid != userId && !User.IsInRole("Admin"))
            {
                return Ok(new R { code = 1, msg = "无权删除此聊天记录" });
            }

            await _chatService.DeleteChatAsync(id);
            return Ok(new R { code = 0, msg = "删除成功" });
        }

        /// <summary>
        /// 分页获取聊天记录
        /// </summary>
        [HttpGet("page")]
        [AllowAnonymous]
        public async Task<ActionResult<R>> GetChatPage(
            [FromQuery] int page = 1,
            [FromQuery] int limit = 10,
            [FromQuery] string sort = "addtime",
            [FromQuery] string order = "desc",
            [FromQuery] string isreply = null)
        {
            try
            {
                // 直接执行简单查询，不使用Include
                var query = _context.Chats
                    .AsNoTracking()  // 添加AsNoTracking()提高性能
                    .Select(c => new
                    {
                        c.id,
                        c.addtime,
                        c.userid,
                        c.adminid,
                        ask = c.LiaoTianNeiRong ?? "",  // 使用LiaoTianNeiRong作为ask字段
                        reply = c.reply ?? "",          // 使用空字符串作为默认值
                        isreply = c.isreply == null ? 0 : c.isreply  // 处理null值，默认为0
                    });

                // 应用筛选条件
                if (!string.IsNullOrEmpty(isreply))
                {
                    if (int.TryParse(isreply, out int isReplyValue))
                    {
                        query = query.Where(c => (c.isreply ?? 0) == isReplyValue);  // 处理null值
                    }
                }

                // 获取总记录数
                var total = await query.CountAsync();

                // 应用排序
                if (!string.IsNullOrEmpty(sort))
                {
                    query = order.ToLower() == "asc" 
                        ? query.OrderBy(c => EF.Property<object>(c, sort))
                        : query.OrderByDescending(c => EF.Property<object>(c, sort));
                }

                // 应用分页
                var chatList = await query
                    .Skip((page - 1) * limit)
                    .Take(limit)
                    .ToListAsync();

                // 如果有结果，获取用户信息
                var result = new List<object>();
                if (chatList.Any())
                {
                    var userIds = chatList.Select(c => c.userid).Distinct().ToList();
                    var users = await _context.Users
                        .AsNoTracking()
                        .Where(u => userIds.Contains(u.id))
                        .Select(u => new { u.id, u.yonghuming })
                        .ToDictionaryAsync(u => u.id, u => u.yonghuming);

                    result = chatList.Select(c => new
                    {
                        c.id,
                        c.addtime,
                        c.userid,
                        c.adminid,
                        ask = c.ask,  // 保持ask字段名称一致
                        c.reply,
                        c.isreply,
                        username = users.GetValueOrDefault(c.userid, "未知用户")
                    }).ToList<object>();
                }

                return Ok(new R
                {
                    code = 0,
                    msg = "获取成功",
                    data = new
                    {
                        total,
                        pageSize = limit,
                        totalPage = (total + limit - 1) / limit,
                        currPage = page,
                        list = result
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error in GetChatPage: {ex.Message}");
                Console.WriteLine($"Stack trace: {ex.StackTrace}");
                
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"Inner exception: {ex.InnerException.Message}");
                }
                
                return Ok(new R
                {
                    code = 1,
                    msg = "获取聊天记录分页数据时发生错误: " + ex.Message,
                    data = null
                });
            }
        }

        /// <summary>
        /// 保存聊天记录
        /// </summary>
        [HttpPost("save")]
        [Authorize]
        public async Task<ActionResult<R>> SaveMessage([FromBody] SaveMessageModel model)
        {
            try
            {
                var userId = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value ?? "0");
                Chat newChat;
                
                // 如果是回复消息
                if (!string.IsNullOrEmpty(model.Reply))
                {
                    if (!User.IsInRole("Admin"))
                    {
                        return Ok(new R { code = 1, msg = "只有管理员可以回复消息" });
                    }

                    // 更新之前的消息状态为未回复
                    var existingChats = await _context.Chats
                        .Where(c => c.userid == model.Userid)
                        .ToListAsync();
                    foreach (var chat in existingChats)
                    {
                        chat.isreply = 0;
                    }
                    await _context.SaveChangesAsync();

                    newChat = new Chat
                    {
                        userid = model.Userid,
                        adminid = userId,
                        reply = model.Reply,
                        addtime = DateTime.Now,
                        isreply = 0
                    };

                    var result = await _chatService.CreateChatAsync(newChat);
                    return Ok(new R { code = 0, msg = "回复成功", data = result });
                }
                // 如果是发送消息
                else if (!string.IsNullOrEmpty(model.Ask))
                {
                    // 更新之前的消息状态为未回复
                    var existingChats = await _context.Chats
                        .Where(c => c.userid == userId)
                        .ToListAsync();
                    foreach (var chat in existingChats)
                    {
                        chat.isreply = 0;
                    }
                    await _context.SaveChangesAsync();

                    newChat = new Chat
                    {
                        userid = userId,
                        LiaoTianNeiRong = model.Ask,
                        addtime = DateTime.Now,
                        isreply = 1
                    };

                    var result = await _chatService.CreateChatAsync(newChat);
                    return Ok(new R { code = 0, msg = "发送成功", data = result });
                }
                else
                {
                    return Ok(new R { code = 1, msg = "消息内容不能为空" });
                }
            }
            catch (Exception ex)
            {
                return Ok(new R { code = 1, msg = "保存失败：" + ex.Message });
            }
        }
    }

    public class SendMessageModel
    {
        public string Message { get; set; }
    }

    public class ReplyMessageModel
    {
        public string Reply { get; set; }
    }

    public class SaveMessageModel
    {
        public string Ask { get; set; }
        public string Reply { get; set; }
        public long Userid { get; set; }
    }
} 